import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_colors.dart';
import 'package:mall/constant/app_dimens.dart';
import 'package:mall/constant/app_strings.dart';
import 'package:mall/constant/text_style.dart';
import 'package:mall/modules/model/address_detail_entity.dart';
import 'package:mall/modules/sc/address_sc.dart';
import 'package:mall/modules/service/mine_service.dart';
import 'package:mall/ui/widgets/divider_line.dart';
import 'package:mall/utils/hud/hud_util.dart';
import 'package:mall/utils/list_placeholder_component/list_placeholder_component.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter/cupertino.dart';

class AddressDetailPage extends StatefulWidget {
  AddressDetailPage();

  @override
  _AddressDetailPageState createState() => _AddressDetailPageState();
}

class _AddressDetailPageState extends State<AddressDetailPage> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _addressDetailController = TextEditingController();

  late final int? addressId = Get.arguments['addressId'];

  late final AddressDetailSc sc_addressDetail;

  final Rxn<AddressDetailEntity> data = Rxn<AddressDetailEntity>();

  // AddressDetailViewModel _model = AddressDetailViewModel();
  // var _addressId;

  @override
  void initState() {
    super.initState();
    // _addressId = widget.addressId;
    // _onRefresh();
    if (addressId != null) {
      sc_addressDetail = Get.put(AddressDetailSc(), tag: addressId.toString());
      sc_addressDetail.addressId = addressId;
      sc_addressDetail.refreshData().then((value) {
        final model = sc_addressDetail.data.value;
        if (model != null) {
          _nameController.text = model.name ?? '';
          _phoneController.text = model.tel ?? '';
          _addressDetailController.text = model.addressDetail ?? '';
          data.value = model;
        }
      });
      ;
    } else {
      data.value = AddressDetailEntity();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: addressId == null ? Text('添加新地址') : Text('修改地址'),
        centerTitle: true,
      ),
      body: Obx(() {
        if (addressId != null) {
          return WrappedListPlaceholderComponent.widget1(
            state: sc_addressDetail.loadState.value,
            data: sc_addressDetail.data.value,
            builder: (p0) => _contentView(data.value!),
          );
        }
        return _contentView(data.value!);
      }),
    );
  }

  Widget _contentView(AddressDetailEntity model) {
    return SafeArea(
        child: Container(
            margin: EdgeInsets.all(15),
            child: SingleChildScrollView(
                child: Column(
              children: [
                Container(
                    child: Card(
                  color: Colors.white,
                  elevation: 0,
                  child: Padding(
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        _nameWidget(),
                        DividerLineView(),
                        _phoneWidget(),
                        DividerLineView(),
                        _addressAreaWidget(model),
                        DividerLineView(),
                        _addressDetailWidget(),
                      ],
                    ),
                  ),
                )),
                SizedBox(height: 15),
                _defaultWidget(model),
                _saveButtonWidget(model),
                _deleteWidget(model)
              ],
            ))));
  }

  Widget _nameWidget() {
    return Container(
      height: 45,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
              left: 0,
              child: Text(
                AppStrings.NAME,
                style: FMTextStyle.color_222222_size_13,
              )),
          Positioned(
              left: 75,
              right: 0,
              child: TextField(
                  maxLines: 1,
                  cursorColor: AppColors.C_FF5722,
                  controller: _nameController,
                  style: FMTextStyle.color_222222_size_13,
                  decoration: InputDecoration(
                    hintText: AppStrings.ADDRESS_PLEASE_INPUT_NAME,
                    hintStyle: FMTextStyle.color_999999_size_13,
                    focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
                  )))
        ],
      ),
    );
  }

  Widget _phoneWidget() {
    return Container(
      height: 45,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
              left: 0,
              child: Text(
                AppStrings.PHONE,
                style: FMTextStyle.color_222222_size_13,
              )),
          Positioned(
            left: 75,
            right: 0,
            child: Container(
                child: TextField(
                    keyboardType: TextInputType.number,
                    maxLines: 1,
                    cursorColor: AppColors.C_FF5722,
                    controller: _phoneController,
                    style: FMTextStyle.color_222222_size_13,
                    decoration: InputDecoration(
                      hintText: AppStrings.ADDRESS_PLEASE_INPUT_PHONE,
                      hintStyle: FMTextStyle.color_999999_size_13,
                      focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: Colors.transparent)),
                    ))),
          )
        ],
      ),
    );
  }

  Widget _addressAreaWidget(AddressDetailEntity model) {
    return Container(
      height: 45,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
              left: 0,
              child: Text(
                AppStrings.ADDRESS_AREA,
                style: FMTextStyle.color_222222_size_13,
              )),
          Positioned(
            left: 75,
            right: 0,
            child: Container(
                child: InkWell(
                    onTap: () => this.show(context),
                    child: Container(
                      alignment: Alignment.centerLeft,
                      height: 60,
                      child: Text(
                        model.addressArea.isEmpty ? AppStrings.ADDRESS_PLEASE_SELECT_CITY : model.addressArea,
                        style: model.addressArea.isEmpty
                            ? FMTextStyle.color_999999_size_13
                            : FMTextStyle.color_222222_size_13,
                      ),
                    ))),
          )
        ],
      ),
    );
  }

  Widget _addressDetailWidget() {
    return Container(
      height: 75,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Positioned(
              left: 0,
              child: Text(
                AppStrings.ADDRESS_DETAIL,
                style: FMTextStyle.color_222222_size_13,
              )),
          Positioned(
            left: 75,
            right: 0,
            child: Container(
                constraints: const BoxConstraints(
                  maxHeight: 75.0,
                  minHeight: 40.0,
                ),
                child: TextField(
                    maxLines: 3,
                    controller: _addressDetailController,
                    style: FMTextStyle.color_222222_size_13,
                    cursorColor: AppColors.C_FF5722,
                    decoration: InputDecoration(
                      hintText: AppStrings.ADDRESS_PLEASE_INPUT_DETAIL,
                      hintStyle: FMTextStyle.color_999999_size_13,
                      border: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.white),
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.white),
                      ),
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.white),
                      ),
                    ))),
          )
        ],
      ),
    );
  }

  Widget _defaultWidget(AddressDetailEntity model) {
    return Card(
      elevation: 0,
      color: Colors.white,
      child: Container(
        padding: EdgeInsets.only(left: 10, right: 10),
        alignment: Alignment.center,
        width: double.infinity,
        height: ScreenUtil().setHeight(AppDimens.DIMENS_150),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
                left: 0,
                child: Text(
                  AppStrings.ADDRESS_SET_DEFAULT,
                  style: FMTextStyle.color_222222_size_13,
                )),
            Positioned(
              right: 10,
              child: Container(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: CupertinoSwitch(
                      value: model.isDefault ?? false,
                      activeColor: AppColors.C_FF5722,
                      onChanged: (bool) {
                        print(bool);
                        data.update((value) => value?.isDefault = bool);
                        // addressDetailViewModel.setDefault(
                        //     bool, _nameController.text, _phoneController.text, _addressDetailController.text);
                      }),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _saveButtonWidget(AddressDetailEntity model) {
    return Container(
      margin: EdgeInsets.only(top: 27.5, left: 15, right: 15),
      width: double.infinity,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: WidgetStateProperty.all(AppColors.C_FF5722),
          shape: WidgetStateProperty.all(
            RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(22.5),
            ),
          ),
          elevation: WidgetStateProperty.all(0),
          textStyle: WidgetStateProperty.all(
            FMTextStyle.color_ffffff_size_13,
          ),
        ),
        onPressed: () => _submit(),
        child: Text(AppStrings.SAVE, style: FMTextStyle.color_ffffff_size_13),
      ),
    );
  }

  Widget _deleteWidget(AddressDetailEntity model) {
    return Visibility(
      visible: !(addressId == null || addressId == 0),
      child: Container(
        margin: EdgeInsets.only(top: 10, left: 15, right: 15),
        width: double.infinity,
        child: RawMaterialButton(
          onPressed: () => _delete(context),
          child: Text(
            AppStrings.ADDRESS_DELETE,
            style: FMTextStyle.color_222222_size_13,
          ),
          elevation: 0,
          highlightElevation: 0,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(
                Radius.circular(22.5),
              ),
              side: BorderSide(color: AppColors.C_999999, width: 1)),
          fillColor: AppColors.C_FFFFFF,
        ),
      ),
    );
  }

  // _onRefresh() {
  //   _model.queryAddressDetail(_addressId);
  // }

  //选择城市
  show(context) {
    CityPickers.showCityPicker(
      context: context,
      itemExtent: 45,
      locationCode: data.value?.areaCode ?? '110000',
      itemBuilder: (item, list, index) {
        return Center(child: Text(item, maxLines: 1, style: FMTextStyle.color_222222_size_13));
      },
    ).then((temp) {
      if (temp == null) return;
      data.update((model) {
        model?.province = temp.provinceName;
        model?.city = temp.cityName;
        model?.county = temp.areaName;
        model?.areaCode = temp.areaId;
      });
    });
    // addressDetailViewModel.setAddressArea(temp.areaId, temp.provinceName, temp.cityName, temp.areaName,
    //     _nameController.text, _phoneController.text, _addressDetailController.text);
  }

  //删除地址dialog
  _delete(BuildContext context) {
    showDialog<void>(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(
              AppStrings.TIPS,
              style: FMTextStyle.color_333333_size_15,
            ),
            content: Text(
              AppStrings.ADDRESS_DELETE_TIPS,
              style: FMTextStyle.color_222222_size_13,
            ),
            actions: <Widget>[
              TextButton(
                style: ButtonStyle(
                  backgroundColor: WidgetStateProperty.all(AppColors.C_FFFFFF),
                ),
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  AppStrings.CANCEL,
                  style: FMTextStyle.color_ff5722_size_13,
                ),
              ),
              TextButton(
                style: ButtonStyle(
                  backgroundColor: WidgetStateProperty.all(AppColors.C_FFFFFF),
                ),
                onPressed: () {
                  Navigator.pop(context);
                  _deleteAddress();
                },
                child: Text(
                  AppStrings.CONFIRM,
                  style: FMTextStyle.color_222222_size_13,
                ),
              ),
            ],
          );
        });
  }

  _submit() {
    // model
    //     .saveAddress(_addressDetailController.text, model.areaId, model.cityName, model.countryName,
    //         _addressId.toString(), model.isDefault, _nameController.text, model.provinceName, _phoneController.text)
    //     .then((response) {
    //   if (response) {
    //     Navigator.pop(context);
    //   }
    // });
    final model = data.value;
    if (model == null) {
      return false;
    }
    if (_nameController.text.toString().isEmpty) {
      HUDUtil.toast(AppStrings.ADDRESS_PLEASE_INPUT_NAME);
      return false;
    }
    if (_phoneController.text.toString().isEmpty) {
      HUDUtil.toast(AppStrings.ADDRESS_PLEASE_INPUT_PHONE);
      return false;
    }
    if (model.addressArea.isEmpty) {
      HUDUtil.toast(AppStrings.ADDRESS_PLEASE_SELECT_CITY);
      return false;
    }
    if (_addressDetailController.text.toString().isEmpty) {
      HUDUtil.toast(AppStrings.ADDRESS_PLEASE_INPUT_DETAIL);
      return false;
    }
    if (_phoneController.text.toString().length != 11) {
      HUDUtil.toast(AppStrings.ADDRESS_PLEASE_INPUT_CORRECT_PHONE);
      return false;
    }
    MineService.addAddress(
      addressDetail: _addressDetailController.text,
      areaCode: model.areaCode!,
      city: model.city!,
      county: model.county!,
      province: model.province!,
      id: model.id.toString(),
      isDefault: model.isDefault,
      name: _nameController.text,
      tel: _phoneController.text,
    ).then((response) {
      if (addressId == null) {
        HUDUtil.toast('保存成功');
      } else {
        HUDUtil.toast('修改成功');
      }
      Navigator.pop(context);
    });
  }

  _deleteAddress() {
    // model.deleteAddress(_addressId).then((response) {
    //   if (response) {
    //     HUDUtil.toast(AppStrings.ADDRESS_DELETE_SUCCESS);
    //     Navigator.pop(context);
    //   } else {
    //     HUDUtil.toast(_model.errorMessage);
    //   }
    // });
    if (addressId == null) {
      return;
    }
    MineService.deleteAddress(addressId!).then((response) {
      HUDUtil.toast(AppStrings.ADDRESS_DELETE_SUCCESS);
      Navigator.pop(context);
    });
  }
}
